# cronmon - Cron e-mail filtering and management
# Copyright (c) 2010 Crown copyright
# 
# This file is part of cronmon.
# 
# cronmon is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# cronmon is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with cronmon.  If not, see <http://www.gnu.org/licenses/>.

from models import *
from cronmon.cron.models import Tag

def tag(message):
    """Compute and store tags applying to a message"""
    tag_all([message])


def tag_all(qs):
    """Tag all messages in a queryset"""
    taggers = []
    for t in TagMatch.objects.enabled():
        t.compile() # cache the compiled regex
        taggers.append(t)
        
    for message in qs:
        body = message.text_body()

        tag_names = set()
        tags = []
        for t in taggers:
            if t.tag in tag_names:
                continue    #skip checking duplicate
            if t.match(message, body=body):
                tag_names.add(t.tag)
                tag, created = Tag.objects.get_or_create(name=t.tag)
                tags.append(tag)


        old_tags = set([t.name for t in message.tags.all()])
        message.tags = tags
        if tag_names != old_tags:
            if tag_names:
                message.add_log_message("Tagged as " + ', '.join(tag_names), type='tag')
            else:
                message.add_log_message("Tags cleared", type='tag')
